//
//  HttpNetworkTool.m
//  NOVASleep
//
//  Created by db J on 2020/10/30.
//  Copyright © 2020 NOVA. All rights reserved.
//

#import "HttpNetworkTool.h"
#import "AFNetworking.h"
static AFHTTPSessionManager *sessionManager;
// 网络状态，初始值-1：未知网络状态
static NSInteger networkStatus = -1;

@implementation HttpNetworkTool

+ (void)load{
    sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@""]];
}

+ (void)GET:(NSString *)URLString  ReadCache:(BOOL)readCache Parameters:(id)parameters Success:(void (^)(id data))success Failure:(void (^)(NSError *error))failure{
    
    [self GET:URLString ReadCache1:readCache Parameters:parameters Success:success Failure:failure];
}

+ (void)POST:(NSString *)URLString  ReadCache:(BOOL)readCache Parameters:(id)parameters Success:(void (^)(id data))success Failure:(void (^)(NSError *error))failure{
    
    [self POST:URLString ReadCache1:readCache Parameters:parameters Success:success Failure:failure];
}

#pragma mark - 带Loading的网络请求
+ (void)GET:(NSString *)URLString  ReadCache1:(BOOL)readCache Parameters:(id )parameters Success:(void (^)(id data))success Failure:(void (^)(NSError *))failure{


    sessionManager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/xml",nil];
    
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    sessionManager.requestSerializer.timeoutInterval = 20.0;
    
    sessionManager.securityPolicy.allowInvalidCertificates = YES;
    //也不验证域名一致性
    sessionManager.securityPolicy.validatesDomainName = NO;
    
    [self setupHeaderField];
    
    NSMutableDictionary * mDic = [NSMutableDictionary dictionaryWithDictionary:parameters];
    
    if (![[mDic objectForKey:@"timeoutInterval"] isEqual:[NSNull null]]) {
        sessionManager.requestSerializer.timeoutInterval = [[mDic objectForKey:@"timeoutInterval"] intValue];
    }

    
    [sessionManager GET:URLString parameters:mDic headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves|NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:nil];
            success(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        
        NSString * errorstr = [error.userInfo objectForKey:@"NSLocalizedDescription"];
        
        if([errorstr rangeOfString:@"Request failed: unauthorized (401)"].location==NSNotFound){
        }
        
        NSLog(@"请求失败:%@",error);
        failure(error);
    }];

}

+ (void)POST:(NSString *)URLString ReadCache1:(BOOL)readCache Parameters:(id)parameters Success:(void (^)(id data))success Failure:(void (^)(NSError *))failure{
    
    sessionManager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/xml",@"application/x-www-form-urlencoded", nil];
    
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    sessionManager.requestSerializer.timeoutInterval = 10.0;
    [sessionManager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    [self setupHeaderField];
    
    sessionManager.securityPolicy.allowInvalidCertificates = YES;
    //也不验证域名一致性
    sessionManager.securityPolicy.validatesDomainName = NO;
    //关闭缓存避免干扰测试
    sessionManager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    
    NSMutableDictionary * mDic = [NSMutableDictionary dictionaryWithDictionary:parameters];
    
    NSLog(@"===post:%@===",mDic);
    
    
    //NSLog(@"开始POST请求:%@\n 参数-------%@",URLString,mDic);
    [sessionManager POST:URLString parameters:mDic headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves|NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:nil];
        if (success) {
            success(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSString * errorstr = [error.userInfo objectForKey:@"NSLocalizedDescription"];
        
        if([errorstr rangeOfString:@"Request failed: unauthorized (401)"].location==NSNotFound){
            
            
        }
        
        failure(error);
    }];

}

/**
 *  设置请求头
 */
+ (void)setupHeaderField{

    NSString * authorization = @"";
    [sessionManager.requestSerializer setValue:authorization forHTTPHeaderField:@"authorization"];
}


#pragma mark -- 网络判断 --
+ (void)checkNetworkLinkStatus{
    //1.创建网络状态监测管理者
    AFNetworkReachabilityManager *reachability = [AFNetworkReachabilityManager sharedManager];
    //2.监听改变
    [reachability setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        /*
         AFNetworkReachabilityStatusUnknown          = -1,
         AFNetworkReachabilityStatusNotReachable     = 0,
         AFNetworkReachabilityStatusReachableViaWWAN = 1,
         AFNetworkReachabilityStatusReachableViaWiFi = 2,
         */
        networkStatus = status;
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"3G|4G");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WiFi");
                break;
            default:
                break;
        }
    }];
    [reachability startMonitoring];
}

/*
 AFNetworkReachabilityStatusUnknown          = -1, 未知网络
 AFNetworkReachabilityStatusNotReachable     = 0,  无网络
 AFNetworkReachabilityStatusReachableViaWWAN = 1,  手机网络
 AFNetworkReachabilityStatusReachableViaWiFi = 2,  Wifi
 */
+ (NSInteger)theNetworkStatus{
    // 调用完checkNetworkLinkStatus,才可以调用此方法
    return networkStatus;
}

@end
